//
//  PrivateMsgDao.m
//  SportSocial
//
//  Created by yull on 15/1/4.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "PrivateMsgDao.h"
#import "PrivateChatMsg.h"

@implementation PrivateMsgDao

+ (instancetype)shareInstance
{
    static PrivateMsgDao *privateDao = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        privateDao = [[PrivateMsgDao alloc] init];
    });
    return privateDao;
}

- (void)createTable
{
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        NSArray *sqlArray = [NSArray arrayWithObjects:
                             @"CREATE TABLE IF NOT EXISTS privateMsg ("
                             "[id] integer NOT NULL PRIMARY KEY AUTOINCREMENT, "
                             "[msgNum] integer,"
                             "[sendId] integer,"
                             "[senderName] varchar,"
                             "[receiveId] integer,"
                             "[content] varchar,"
                             "[decodeContent] varchar,"
                             "[createTime] integer,"
                             "[msgType] integer,"
                             "[roleType] integer,"
                             "[msgSubType] integer,"
                             "[msgLength] integer,"
                             "[isRead] integer,"
                             "[isAck] integer,"
                             "[url] varchar,"
                             "[bigImageUrl] varchar,"
                             "[localPath] varchar,"
                             "[sendStatus] integer,"
                             "[picUploadPercent] double,"
                             "[retainField] varchar,"
                             "[icon] varchar)",nil];
        [db beginTransaction];
        BOOL result = YES;
        for (NSString *sql in sqlArray) {
            result &= [db executeUpdate:sql];
        }
        if (result) {
            result &= [db commit];
        }
        
        if (!result) {
            [db rollback];
        }
    }];
}

- (BOOL)insertPrivateChatMsg:(PrivateChatMsg *)privateChatMsg
{
    __block BOOL result = YES;
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"insert into privateMsg (msgNum,sendId,senderName,receiveId,content,decodeContent,createTime,msgType,roleType,msgSubType,msgLength,isRead,isAck,url,bigImageUrl,localPath,sendStatus,picUploadPercent,retainField,icon) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                  [NSNumber numberWithLongLong:privateChatMsg.msgNum],
                  [NSNumber numberWithLongLong:privateChatMsg.sendId],
                  privateChatMsg.senderName,
                  [NSNumber numberWithLongLong:privateChatMsg.receiveId],
                  privateChatMsg.content,
                  privateChatMsg.decodeContent,
                  [NSNumber numberWithLongLong:privateChatMsg.createTime],
                  [NSNumber numberWithInteger:privateChatMsg.msgType],
                  [NSNumber numberWithInteger:privateChatMsg.roleType],
                  [NSNumber numberWithInteger:privateChatMsg.msgSubType],
                  [NSNumber numberWithInteger:privateChatMsg.msgLength],
                  [NSNumber numberWithInteger:privateChatMsg.isRead],
                  [NSNumber numberWithInteger:privateChatMsg.isAck],
                  privateChatMsg.url,
                  privateChatMsg.bigImageUrl,
                  privateChatMsg.localPath,
                  [NSNumber numberWithInteger:privateChatMsg.sendStatus],
                  [NSNumber numberWithFloat:privateChatMsg.picUploadPercent],
                  privateChatMsg.retainField,
                  privateChatMsg.icon];
        
        if (result) {
            privateChatMsg.dbId = db.lastInsertRowId;
        }
    }];
    return result;
}

//更新消息发送状态
- (BOOL)updateSendStatusWithDbId:(UInt64)dbId status:(ChatMsgSendStatus)status
{
    __block BOOL result = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"update privateMsg set sendStatus=? where id=?",[NSNumber numberWithInteger:status],[NSNumber numberWithLongLong:dbId]];
    }];
    return result;
}

#pragma mark - 收到消息
- (BOOL)checkExistWithChatMsg:(PrivateChatMsg *)chatMsg
{
    __block BOOL result = NO;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
       FMResultSet *resultSet = [db executeQuery:@"select * from privateMsg where msgNum=? and roleType=?",[NSNumber numberWithLongLong:chatMsg.msgNum],
                 [NSNumber numberWithUnsignedInteger:ChatMsgRoleTypeReceive]];
        if (resultSet.next) {
            result = YES;
            chatMsg.dbId = [resultSet longLongIntForColumn:@"id"];
        }
        [resultSet close];
    }];
    return result;
}

- (BOOL)updateChatMsg:(PrivateChatMsg *)chatMsg
{
    __block BOOL result = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"update privateMsg set msgNum=?,sendId=?,senderName=?,receiveId=?,content=?,decodeContent=?,createTime=?,msgType=?,roleType=?,msgSubType=?,msgLength=?,isRead=?,isAck=?,url=?,bigImageUrl=?,localPath=?,sendStatus=?,picUploadPercent=?,retainField=?,icon=? where id=?",[NSNumber numberWithLongLong:chatMsg.msgNum],
                  [NSNumber numberWithLongLong:chatMsg.sendId],
                  chatMsg.senderName,
                  [NSNumber numberWithLongLong:chatMsg.receiveId],
                  chatMsg.content,
                  chatMsg.decodeContent,
                  [NSNumber numberWithLongLong:chatMsg.createTime],
                  [NSNumber numberWithInteger:chatMsg.msgType],
                  [NSNumber numberWithInteger:chatMsg.roleType],
                  [NSNumber numberWithInteger:chatMsg.msgSubType],
                  [NSNumber numberWithInteger:chatMsg.msgLength],
                  [NSNumber numberWithInteger:chatMsg.isRead],
                  [NSNumber numberWithInteger:chatMsg.isAck],
                  chatMsg.url,
                  chatMsg.bigImageUrl,
                  chatMsg.localPath,
                  [NSNumber numberWithInteger:chatMsg.sendStatus],
                  [NSNumber numberWithFloat:chatMsg.picUploadPercent],
                  chatMsg.retainField,
                  chatMsg.icon,
                  [NSNumber numberWithLongLong:chatMsg.dbId]];
    }];
    return result;
}

//更新一条接收消息
- (BOOL)addPrivateChatMsg:(PrivateChatMsg *)chatMsg
{
    BOOL exist = [self checkExistWithChatMsg:chatMsg];
    if (exist) {
        return [self updateChatMsg:chatMsg];
    }else {
        return [self insertPrivateChatMsg:chatMsg];
    }
}

//接收到消息数组
- (BOOL)receivePrivateChatMsgArray:(NSArray *)chatMsgArray
{
    BOOL result = YES;
    
    for (PrivateChatMsg *chatMsg in chatMsgArray) {
        result &= [self addPrivateChatMsg:chatMsg];
    }
    return result;
}

//查找所有聊天
- (NSArray *)selectAllPrivateMsgArrayWithUser:(UInt64)userId
{
    __block NSMutableArray *msgArray = [NSMutableArray array];
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = [db executeQuery:@"select * from (select * from privateMsg where sendId=? or receiveId=? order by id desc limit(10)) order by id asc",[NSNumber numberWithLongLong:userId],[NSNumber numberWithLongLong:userId]];
        while (resultSet.next) {
            [msgArray addObject:[PrivateChatMsg privateChatMsgWithResutlSet:resultSet]];
        }
        [resultSet close];
    }];
    return msgArray;
}

- (NSArray *)selectHistoryPrivateMsgArrayWithUser:(UInt64)userId dbId:(UInt64)dbId
{
    __block NSMutableArray *msgArray = [NSMutableArray array];
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = [db executeQuery:@"select * from (select * from privateMsg where ((sendId=? or receiveId=?) and id<?) order by id desc limit(10)) order by id asc",[NSNumber numberWithLongLong:userId],[NSNumber numberWithLongLong:userId],[NSNumber numberWithLongLong:dbId]];
        while (resultSet.next) {
            [msgArray addObject:[PrivateChatMsg privateChatMsgWithResutlSet:resultSet]];
        }
        [resultSet close];
    }];
    return msgArray;
}

- (BOOL)updateMsgId:(UInt64)msgId preview:(NSString *)preview original:(NSString *)original
{
    __block BOOL result = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"update privateMsg set url=?,bigImageUrl=? where id=?",preview,original,[NSNumber numberWithLongLong:msgId]];
    }];
    return result;
}

- (BOOL)updateReadWithDBId:(UInt64)dbId
{
    __block BOOL result = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"update privateMsg set isRead=? where id=?",[NSNumber numberWithBool:YES],[NSNumber numberWithLongLong:dbId]];
    }];
    return result;
}

- (NSArray *)selectAllPicMsgWithUserId:(UInt64)userId
{
    __block NSMutableArray *array = [NSMutableArray array];
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *result = [db executeQuery:@"select * from privateMsg where msgType=? and (sendId=? or receiveId=?)",[NSNumber numberWithInteger:ChatMsgTypePic],[NSNumber numberWithLongLong:userId],[NSNumber numberWithLongLong:userId]];
        while (result.next) {
            [array addObject:[PrivateChatMsg privateChatMsgWithResutlSet:result]];
        }
        [result close];
    }];
    return array;
}

- (BOOL)clearSendingMessageToFail
{
    __block BOOL result = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"update privateMsg set sendStatus=? where sendStatus=?",[NSNumber numberWithInteger:ChatMsgSendStatusFail],[NSNumber numberWithInteger:ChatMsgSendStatusSending]];
    }];
    return result;
}

- (BOOL)deleteAllMsgWithUserId:(UInt64)userId
{
    __block BOOL result = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"delete from privateMsg where sendId=? or receiveId=?",[NSNumber numberWithLongLong:userId],[NSNumber numberWithLongLong:userId]];
    }];
    return result;
}
@end
